import router from "@/router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import useUserStore from "@/store/modules/user";
import pinia from "@/store";
import setting from "@/setting";

nprogress.configure({ showSpinner: false });

const userStore = useUserStore(pinia);

router.beforeEach(async (to, from, next) => {
  nprogress.start();
  document.title = `${setting.title} - ${to.meta.title}`;
  let token = userStore.token;
  let username = userStore.username;
  if (token) {
    if (to.path == "/login") {
      next({ path: from.path });
    } else {
      if (username) {
        next();
      } else {
        try {
          await userStore.userInfo();
          next();
        } catch (error) {
          next({ path: "/login", query: { redirect: from.path } });
        }
      }
    }
  } else {
    if (to.path == "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});

router.afterEach((to, from) => {
  nprogress.done();
});
